import { login as loginApi, getCurrentDoctor as getCurrentDoctorApi } from '@/api/auth'

interface AuthState {
  token: string | null
  user: any | null
  isLoggedIn: boolean
}

const auth = {
  namespaced: true,
  state: (): AuthState => ({
    token: null, // 将由vuex-along从localStorage恢复
    user: null,
    isLoggedIn: false
  }),
  mutations: {
    SET_TOKEN(state, token: string) {
      state.token = token
      state.isLoggedIn = !!token
      // 确保token保存到localStorage
      if (token) {
        localStorage.setItem('token', token)
      }
    },
    SET_USER(state, user: any) {
      state.user = user
    },
    CLEAR_AUTH(state) {
      state.token = null
      state.user = null
      state.isLoggedIn = false
      // 清除localStorage中的token
      localStorage.removeItem('token')
    }
  },
  actions: {
    async login({ commit }, credentials: { username: string; password: string }) {
      try {
        const response = await loginApi(credentials)
        if (response.success) {
          const { token, user } = response.data
          commit('SET_TOKEN', token)
          commit('SET_USER', user)
          return { success: true, data: response.data }
        } else {
          return { success: false, message: response.message }
        }
      } catch (error) {
        console.error('Login error:', error)
        return { success: false, message: '登录失败，请稍后重试' }
      }
    },

    async logout({ commit }) {
      commit('CLEAR_AUTH')
    },

    async getCurrentUser({ commit, state }) {
      if (!state.token) {
        return { success: false, message: '未登录' }
      }

      try {
        const response = await getCurrentDoctorApi()
        if (response.success) {
          commit('SET_USER', response.data)
          return { success: true, data: response.data }
        } else {
          return { success: false, message: response.message }
        }
      } catch (error) {
        console.error('Get current user error:', error)
        commit('CLEAR_AUTH')
        return { success: false, message: '获取用户信息失败' }
      }
    },

    restoreAuth({ commit, dispatch }) {
      // vuex-along会自动恢复token，只需处理后续逻辑
      dispatch('getCurrentUser')
    }
  },
  getters: {
    isAuthenticated: (state) => state.isLoggedIn && !!state.token,
    currentUser: (state) => state.user,
    userRole: (state) => state.user?.role,
    userName: (state) => state.user?.real_name || state.user?.username,
    userDepartment: (state) => state.user?.department
  }
}

export default auth